package com.hgy.carsb.service;

import com.hgy.carsb.entity.IndicatorDetail;
import com.hgy.carsb.entity.Total;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class RatioService {

    @Autowired
    private InfoService infoService;

    public Total getTotal(int year, int month, String code1, String code2, String prefix){
        Total data = new Total();
        String thisMonth = infoService.getRatio(year, month, code1, code2, prefix);
        String lastYear = infoService.getRatio(year-1, month, code1, code2, prefix);
        String lastMonth;
        if (month==1){
            lastMonth = infoService.getRatio(year-1, 12, code1, code2, prefix);
        }else {
            lastMonth = infoService.getRatio(year, month-1, code1, code2, prefix);
        }
        BigDecimal thisMonthNum = new BigDecimal(thisMonth);
        BigDecimal lastYearNum = new BigDecimal(lastYear);
        BigDecimal lastMonthNum = new BigDecimal(lastMonth);
        data.setSum(thisMonth);
        BigDecimal subMonth = thisMonthNum.subtract(lastMonthNum);
        BigDecimal subYear = thisMonthNum.subtract(lastYearNum);
        if (subMonth.compareTo(new BigDecimal(0))==0){
            subMonth = new BigDecimal(0);
        }else {
            subMonth = subMonth.multiply(new BigDecimal(100)).divide(lastMonthNum, 2,BigDecimal.ROUND_HALF_UP);
        }
        if (subYear.compareTo(new BigDecimal(0))==0){
            subYear = new BigDecimal(0);
        }else {
            subYear = subYear.multiply(new BigDecimal(100).divide(lastYearNum, 2,BigDecimal.ROUND_HALF_UP));
            subYear = subYear.setScale(2, BigDecimal.ROUND_HALF_UP);
        }
        if (subMonth.compareTo(new BigDecimal(0))<0){
            data.setMonthFlag(false);
        }else {
            data.setMonthFlag(true);
        }
        if (subYear.compareTo(new BigDecimal(0))<0){
            data.setYearFlag(false);
        }else {
            data.setYearFlag(true);
        }
        data.setMonthRate(subMonth.abs().toString());
        data.setYearRate(subYear.abs().toString());
        return data;
    }
}
